// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {

        hpLb: {
            default: null,
            type: cc.Label
        },


        biuAudio: {
            default: null,
            type: cc.AudioClip
        },

        boomAudio: {
            default: null,
            type: cc.AudioClip
        },
        hp: 0,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {

        this.RigidBody = this.getComponent(cc.RigidBody);
        let velocity = this.RigidBody;
        velocity.linearVelocity.x = 0;
        velocity.linearVelocity.y = 0;
        this.RigidBody = velocity;

        this.isDead = false;
    },

    start () {

    },

    initInfo(conf, manager){

        //随机横向速度
        let xv = conf.xvMin + Math.random() * (conf.xvMax - conf.xvMin);
        xv = Math.floor(xv);
        this.hp = conf.hpMin + Math.random() * (conf.hpMax - conf.hpMin);
        this.hp = Math.floor(this.hp);

        this.hpLb.string = this.hp;
        let size = conf.sizeMin + Math.random() * (conf.sizeMax - conf.sizeMin);
        size = size / 100;
        if (Math.random() > 0.5) {
            xv *= -1;
        }
        //随机横向速度
        this.RigidBody.linearVelocity = cc.v2(xv, 0);
        this.node.setScale(size);
        this.node.group = 'Enemy';

        this.manager = manager;
    },

    playBeAttackAudio(){
        cc.audioEngine.playEffect(this.biuAudio, false);
    },

    playDeadAudio(){
        cc.audioEngine.playEffect(this.boomAudio, false);
    },

    update (dt) {
         if (this.hp == 0 && this.isDead) {
            this.manager.delEnemy(this.node);
            this.isDead = false;

        }
    },

    onBeginContact: function (contact, selfCollider, otherCollider) {

        if (otherCollider.node.group == 'Bullet') {
            let bulletInfo = otherCollider.getComponent('Bullet').info;
            let hurt = bulletInfo.hurt * bulletInfo.xArray.length;
            if(hurt > this.hp) hurt = this.hp;
            this.hp -= hurt;
            this.manager.game.addScore(hurt);
            this.hpLb.string = this.hp;
            if (this.hp == 0) {
                // this.node.group = 'default';
                this.playDeadAudio();
                this.manager.game.drawEffect(this.node, 1, 'boom1');
                this.isDead = true;

                // this.manager.delEnemy(this.node);

            }else{
                this.playBeAttackAudio();
                this.manager.game.drawEffect(otherCollider.node, 1, 'death1');
            }
        }

    },
});
